package br.com.nemesis.jsf.listener;

import br.com.nemesis.web.Sessao;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;

public class AutenticacaoListener implements PhaseListener {

    public void afterPhase(PhaseEvent pe) {
    }

    public void beforePhase(PhaseEvent pe) {
        FacesContext contexto = FacesContext.getCurrentInstance();
        Sessao sessao = (Sessao) contexto.getApplication().evaluateExpressionGet(
                contexto, "#{sessao}", Sessao.class);
        if(sessao.getUsuario()==null){
            ViewHandler viewHandler = contexto.getApplication().getViewHandler();
            UIViewRoot viewRoot = viewHandler.createView(contexto,"/login.xhtml");
            contexto.setViewRoot(viewRoot);
        }
    }

    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }

}